<template>
	<view class="x-main-content">
		<view v-if="detailObj.name == '代办跑腿'" class="bgimg" style="background-image: url('https://peiyiwang.obs.cn-east-3.myhuaweicloud.com:443/file%2F9358062556658764.jpg')">
			<image class="left" src="../../static/icon/left_back.png" @click="leftClick()"></image>
		</view>
		<view v-else  class="bgimg" style="background-image: url('https://peiyiwang.obs.cn-east-3.myhuaweicloud.com:443/file%2F3050399651165424.png')">
			<image class="left" src="../../static/icon/left_back.png" @click="leftClick()"></image>
		</view>
		<view class="form_content">
			<view style="padding: 30rpx;">
				<view class="bt">
					<image :src="detailObj.name == '代办跑腿' ? '../../static/home/dbpt.png': 'https://peiyiwang.obs.cn-east-3.myhuaweicloud.com:443/file%2F6774473955918281.png'" mode=""></image>
					<text class="btn-txt">您现在正在办理[{{detailObj.name}}]下单服务，请如实填写信息。</text>
					<text class="des" v-show="detailObj.introduction != null">{{detailObj.introduction}}</text>
				</view>
				<u-form :model="form" :rules="rules" ref="uForm" :label-style="labelStyle" errorType="toast">
					<u-form-item label="价格(元)" borderBottom>
						<u-input v-model="detailObj.price" disabled placeholderClass="plaClass"
								 disabledColor="#ffffff" border="none"></u-input>
					</u-form-item>
					<u-form-item @click="goChooseHospital()" label="请选择医院" prop="hospital" borderBottom>
						<u-input v-model="form.hospital" disabled placeholderClass="plaClass" disabledColor="#ffffff"
							placeholder="选择医院" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item @click="goChooseDepart()" label="请选择科室" prop="hospital" borderBottom>
						<u-input v-model="form.departmentName" disabled placeholderClass="plaClass"
								 disabledColor="#ffffff" placeholder="选择科室" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item @click="goChooseDoctor()" label="请选择医生" prop="hospital" borderBottom>
						<u-input v-model="form.doctorName" disabled placeholderClass="plaClass"
								 disabledColor="#ffffff" placeholder="选择医生" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item @click="goPatients()" label="请选择就诊人" prop="patients" borderBottom>
						<u-input v-model="form.patients" disabled placeholderClass="plaClass" disabledColor="#ffffff"
							placeholder="选择就诊人" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
<!--					<u-form-item @click="goSelectDepartment()" label="请选择科室" prop="administrativeOffice" borderBottom>-->
<!--						<u-input v-model="form.administrativeOffice" disabled placeholderClass="plaClass"-->
<!--							disabledColor="#ffffff" placeholder="选择科室" border="none"></u-input>-->
<!--						<u-icon slot="right" name="arrow-right"></u-icon>-->
<!--					</u-form-item>-->
					<u-form-item label="请选择类型" prop="serviceType" borderBottom>
						<u-radio-group v-model="form.serviceType" placement="row">
							<u-radio v-for="(item, index) in lists" :key="index" :label="item.name" :name="item.name"
									 @change="radioChange">
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="请选择服务时间" prop="appointmentDate" borderBottom @click="dateShow=true">
						<u-input v-model="form.appointmentDate" disabled placeholderClass="plaClass"
							disabledColor="#ffffff" placeholder="选择服务时间" border="none"></u-input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<view style="padding-left: 15px;">
						<view style="font-size: 14px;color: #333;padding-top: 10px;">特殊需求</view>
						<u-form-item class="sepclial" prop="specifyInfo">
							<u-textarea v-model="form.specifyInfo" placeholder="请填写您的特殊需求" confirmType="done"
										placeholderStyle="font-size: 28rpx;font-family: PingFangSC-Light, PingFang SC;font-weight: 300;color: #6F7DA2;letter-spacing: 1px;">
							</u-textarea>
						</u-form-item>
					</view>
				</u-form>
				<view class="btn-box" style="padding: 0 20rpx;margin-top: 60rpx;">
					<view class="btn">
						<u-button text="下单" :hairline="false" :customStyle="commonBtnStyle" color="#386FFF"
							@click="goBuy"></u-button>
					</view>
				</view>
			</view>
		</view>
		<u-datetime-picker ref="datetimePicker" :show="dateShow" mode="datetime" v-model="timeOptions.value"
			:minDate="timeOptions.min" :maxDate="timeOptions.max" :formatter="formatter" @cancel="dateCancel"
			@confirm="dateConfirm">
		</u-datetime-picker>
		<view :show="flag">
			<view v-if="flag" @click="flag = false" style="position: absolute;top: 0;left:0;width: 100%;height: 100%;background: #000;z-index: 99;opacity: 0.2"></view>
			<u-picker :show="flag" :columns="showPickerList" :keyName="pickerType == 'depart' ? 'dictLabel' : 'doctorName'" @confirm="onConfirm" @cancel="isClose"></u-picker>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showPickerList:[],
				pickerType:'',
				flag:false,
				lists: [{
					name: '专家',
					disabled: false
				},
					{
						name: '普通',
						disabled: false
					}
				],
				openId:'',
				detailObj:{},
				index: 0,
				goodsid:'',
				form: {
					hospital: "", //医院
					hospitalId: "",
					appointmentDate: "", // 时间
					specifyInfo: "", // 特殊需求
					patients: "", //就诊人
					contactPhone:"",
					idCardNumber:"",
					administrativeOffice: "", //科室
					serviceType: "", // 服务类型
					departmentId:"",
					departmentName:"",
					doctorId:"",
					doctorName:"",
				},
				dateShow: false,
				timeOptions: {
					value: 0,
					max: 0,
					min: 0
				},
				labelStyle: {
					color: '#333',
					fontSize: '14px',
					textAlign: 'left',
					fontWeight: '400',
					letterSpacing: '1px',
					fontFamily: 'PingFangSC - Regular,PingFang SC'
				},
				rules: {
					hospital: [{
						require: true,
						message: '请选择医院',
						trigger: ['blur', 'change']
					}],
					patients: [{
						require: true,
						message: '请选择就诊人',
						trigger: ['blur', 'change']
					}],
					administrativeOffice: [{
						require: true,
						message: '请选择科室',
						trigger: ['blur', 'change']
					}],
					appointmentDate: [{
						require: true,
						message: '请选择时间',
						trigger: ['blur', 'change']
					}],
				}
			}
		},
		onLoad(option) {
			let openId = uni.getStorageSync('openId')
			if(openId){
				this.openId = openId
			}
			this.timeOptions.value = Number(new Date())
			// 预计+14天
			this.timeOptions.max = new Date('2100-01-01').getTime()
			let currentTime = new Date()
			currentTime.setHours(currentTime.getHours()+2)
			this.timeOptions.min = Number(currentTime)
			
			// 获取当前页面实例
			// const pages = getCurrentPages();
			// const currentPage = pages[pages.length - 1];
			// 获取页面链接携带的参数
			// var urlParams = currentPage.options;
			this.getDetail(option.id)
			uni.$on('hospital',this.resHospitall)
			uni.$on('patients',(patientSelection)=>{
				this.form.patients = patientSelection.name
				this.form.contactPhone = patientSelection.phone
				this.form.idCardNumber = patientSelection.idCard
			})
		},
		onShow(){
		},
		methods: {
			onConfirm(e){
				let list = e.value
				if(this.pickerType == 'depart'){
					this.form.departmentId = list[0].parentId
					this.form.departmentName = list[0].dictLabel
					this.form.doctorId = ''
					this.form.doctorName = ''
					this.getAllHospitalDoctorList()
				}
				if(this.pickerType == 'doctor'){
					this.form.doctorId = list[0].id
					this.form.doctorName = list[0].doctorName
				}
				this.flag = false
			},
			goChooseDepart(){
				if(!this.form.hospital){
					this.$u.toast('请先选择医院')
					return
				}
				this.pickerType = 'depart'
				this.getFirstDepartmentList()
				this.$nextTick(()=>{
					this.flag = true
				})
			},
			goChooseDoctor(){
				if(!this.form.departmentName){
					this.$u.toast('请先选择科室')
					return
				}
				this.pickerType = 'doctor'
				this.$nextTick(()=>{
					this.flag = true
				})
			},
			isClose() {
				this.flag = false
			},
			async getFirstDepartmentList(){
				this.showPickerList = []
				let ret = await this.$request('/api/index/getFirstDepartmentList/' + this.form.hospitalId)
				this.showPickerList = [ret.data.data]
			},
			async getAllHospitalDoctorList(){
				this.showPickerList = []
				let data = {
					hospitalId: this.form.hospitalId,
					parentId: this.form.departmentId
				}
				let res = await this.$request('/api/index/getAllHospitalDoctorList/', data, 'GET')
				this.showPickerList = [res.data.rows]
			},
			radioChange(n) {
				console.log('radioChange', n);
				if(n == '专家'){
					this.form.serviceType = 1
				}
				if(n == '普通'){
					this.form.serviceType = 2
				}
			},
			async getDetail(id){
				let data = {}
				let res = await this.$request(`/api/service/detail/${id}`, data, 'GET')
				this.$nextTick(()=>{
					this.detailObj = res.data.data
				})
			},
			resHospitall(hospital1){
				if(this.form.hospital != hospital1.name){
					this.form.departmentId = ''
					this.form.departmentName = ''
					this.form.doctorId = ''
					this.form.doctorName = ''
				}
				this.form.hospital = hospital1.name
				this.form.hospitalId = hospital1.id
			},
			goSelectDepartment() {
				if(!this.form.hospital){
					this.$u.toast('请先选择医院')
					return
				}
				this.$u.route({
					url: 'pages/business/components/selectDepartment'
				})
			},
			leftClick() {
				uni.navigateBack({
					delta: 1
				});
			},
			goChooseHospital() {
				this.$u.route({
					url: 'pages/business/components/chooseHospitals'
				})
			},
			goPatients() {
				this.$u.route({
					url: 'pages/business/components/patients'
				})
			},
			dateConfirm(e) {
				// console.log('value', e)
				// this.params.appointmentDate = e[0]
				this.form.appointmentDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
				this.dateCancel()
			},
			dateCancel() {
				this.dateShow = false
			},
			formatter(type, value) {
				// console.log('type', type)
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			async getOpenId(){
				if(!this.openId){
					let getId = await this.uniLogin()
					return getId
				}
				return this.openId
			},
			async uniLogin(){
				let code = await this.getcode()
				return this.getIdByCode(code)
			},
			async getcode(){
				return new Promise((resolve,reject)=>{
					uni.login({
						provider: 'weixin',
						success: res => {
							resolve(res.code)
						}
					})
				})
			},
			async getIdByCode(code){
				let phoneNumber = uni.getStorageSync('userInfo').phonenumber
				let params = {
					code: code,
					phoneNumber
				}
				let resId = await this.$request('/api/applet/getOpenId', params, 'get').then(res=>{
					let openId = res.data.data.openid
					uni.setStorageSync('openId',openId)
					this.openId = openId
					return openId
				}).catch(err=>{
					uni.hideLoading()
					return this.openId
				})
				return resId
			},
			goBuy() {
				if(!this.form.hospital){
					this.$u.toast('请选择医院')
					return
				}
				if(!this.form.departmentName){
					this.$u.toast('请选择科室')
					return
				}
				if(!this.form.doctorName){
					this.$u.toast('请选择医生')
					return
				}
				if(!this.form.patients){
					this.$u.toast('请选择就诊人')
					return
				}
				if(!this.form.serviceType){
					this.$u.toast('请选择类型')
					return
				}
				if(!this.form.appointmentDate){
					this.$u.toast('请选择服务时间')
					return
				}
				if(!this.form.specifyInfo){
					this.$u.toast('请选择特殊需求')
					return
				}
				let chooseTime = new Date(this.form.appointmentDate).getHours()
				console.log(chooseTime)
				if((chooseTime>=17 && chooseTime<=24) || (chooseTime>=0 && chooseTime<=7)){
					uni.showModal({
						title: '提示',
						content: '所有订单的订单金额根据陪诊时段有相应的差别，17点-22点(含)，价格订单金额的1.2倍，23-7点(含)，价格订单金额的1.5倍，其他时间为套餐价格',
						success: res => {
							if (res.confirm) {
								this.submitFn()
							}
							if (res.cancel) {}
						}
					})
					return
				}
				this.submitFn()
			},
			async submitFn(){
				let _this = this
				let params = {
					// "acceptUserId": 0,
					// "address": "",
					"amount": _this.detailObj.price,
					"appointmentDate": _this.form.appointmentDate,
					"buyType": 1,
					"contactName": _this.form.patients,
					"contactPhone": _this.form.contactPhone,
					// "drugType": "",
					"hospitalId": _this.form.hospitalId,
					"idCardNumber": _this.form.idCardNumber,
					"num": 1,
					"productId": _this.detailObj.id,
					"registrationType": _this.form.administrativeOffice,
					"specialNeeds": _this.form.specifyInfo,
					"departmentId": _this.form.departmentId,
					"doctorId": _this.form.doctorId
				}
				let res = await this.$request('/api/serviceOrder/submitServiceOrder', params, 'POST','type')
				console.log("res",res)
				if(res.data.code == 200){
					this.recharge(res.data.data)
				}
			},
			async recharge(res){
				uni.showLoading({
					title: "请求中..."
				})
				let _this = this
				// res.data.data.amount.serviceOrderSn
				let openId = await this.getOpenId()
				let params ={
					"isCustomize": "0",
					"openId": openId,
					"orderNum": res.serviceOrderSn,
					"payType": "WX_APPLET_PAY",
					"paymentAmount": res.amount,
					"rechargeAmount": 0,
				}
				let resVal = await this.$request('/api/userAccount/recharge', params, 'POST','type')
				console.log('resVal',resVal)
				uni.hideLoading();
				if(resVal.data.code == 200){
					let resData = resVal.data.data
					wx.requestPayment({
						timeStamp: resData.timeStamp,
						nonceStr: resData.nonceStr,
						package: 'prepay_id=' + resData.prepay_id,
						signType: 'MD5',
						paySign: resData.paySign,
						success (res) {
							_this.$u.route({
								url: '/packageA/pages/order/order',
								params: {
									label: 3,
									back:2
								}
							})
						},
						fail (res) {
							console.log('failres',res)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.bgimg {
		width: 100%;
		height: 200px;
		position: absolute;
		// box-sizing: border-box;
		background-size: 100%;
		background-repeat: no-repeat;

		.left {
			width: 8px;
			height: 16px;
			margin-left: 50rpx;
			margin-top: 78rpx;
		}

	}

	.form_content {
		position: absolute;
		margin-top: 170px;
		margin-left: 20rpx;
		margin-right: 20rpx;
		width: calc(100vw - 20px);
		// height: calc(100vh - 180px);
		height: 100vh;
		background: #ffffff;
		border-radius: 30rpx 30rpx 0 0;

		.bt {
			padding: 0 20rpx;
			display: flex;
			flex-direction: column;
			border-bottom: 1px solid rgb(214, 215, 217);

			image {
				width: 115rpx;
				height: 50rpx;
			}

			.btn-txt {
				font-size: 26rpx;
				font-family: PingFangSC-Light, PingFang SC;
				font-weight: 300;
				color: #777777;
				letter-spacing: 1px;
				margin-top: 8rpx;
				margin-bottom: 0rpx;
			}
			.des {
				font-size: 26rpx;
				font-family: PingFangSC-Light, PingFang SC;
				font-weight: 300;
				color: #777777;
				letter-spacing: 1px;
				margin-top: 10rpx;
				margin-bottom: 24rpx;
			}
		}
	}

	.plaClass {
		text-align: right;
		font-size: 28rpx;
		font-family: PingFangSC-Light, PingFang SC;
		font-weight: 300;
		color: #6F7DA2;
		letter-spacing: 1px;
		margin-right: 10px;
	}

	/deep/ .u-form-item__body__left {
		width: 20vh !important;
		margin-left: 10px;
	}

	/deep/.u-form-item__body {
		padding: 15px 0 !important;
	}

	/deep/.item__body__right__content__icon {
		margin-left: 10rpx;
	}

	/deep/.u-radio-group--row {
		justify-content: space-around;
	}

	.sepclial {
		/deep/.u-form-item__body {
			flex-direction: column !important;
		}

		/deep/.u-form-item__body__right__content {
			margin-top: 15px !important;
			padding: 0 9px !important;
		}

		.u-textarea {
			background: #F4F6FA;
			border-radius: 20rpx;
		}

		.u-border {
			border-style: none
		}
	}
</style>
